package com.sugar.web.struts.system.privilege;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sugar.base.util.Const;
import com.sugar.base.util.ConverterJSON;
import com.sugar.domain.oa.hr.EmpAccount;
import com.sugar.domain.oa.hr.Employee;
import com.sugar.service.oa.hr.IEmpAccountService;
import com.sugar.web.struts.BaseActionSupport;

@Controller
@Scope("prototype")
public class LoginSystemAction extends BaseActionSupport {

	private Log log = LogFactory.getLog(getClass()) ;
	
	private static final long serialVersionUID = 1L;
	
	private EmpAccount account ;
	
	@Resource
	private IEmpAccountService eas ;
	
	public EmpAccount getAccount() {
		return account;
	}

	public void setAccount(EmpAccount account) {
		this.account = account;
	}

	/**
	 * 用户登录验证
	 * @return
	 */
	public void loginCheck() {
		try {
			account = this.eas.findEmpAccountByParamDao(account) ;
			
			if(null != account) {
			
				Map<Object,Object> map = new HashMap<Object,Object>();
				map.put("account", account);
				
				PrintWriter out = getResponse().getWriter() ;
				
				//格式化为JSON格式
				String accountStr = ConverterJSON.generate(map, ConverterJSON.filterBean("emp")).toString() ;
				
				//通过账号获得员工个人信息保存Session
				getRequest().getSession().setAttribute(Const.USER_SESSION_KEY, account.getEmp()) ;
				
				//向客户端输出JSON数据
				out.write(accountStr) ;
				
				out.close() ;
			} else {
				log.info("[....Log4j]：该登录账号不存在...") ;
			}
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}
	
	public String userLogout() throws Exception {
		Employee e = (Employee) getRequest().getSession().getAttribute(Const.USER_SESSION_KEY) ;
		if(null != e) {
			log.info("注销用户：" + e.getEmpRealname()) ;
			getRequest().getSession().removeAttribute(Const.USER_SESSION_KEY) ;
		}
		
		return "logout" ;
	}
	
	/*public String getEmployeeInfo() throws Exception {
		
		Employee emp = (Employee) getRequest().getSession().getAttribute("emp") ;
		
		Map<Object,Object> map = new HashMap<Object,Object>();
		map.put("emp", emp) ;
		
		System.out.println(emp.getEmpRealname() + "--" + emp.getDept().getDeptName());
		
		PrintWriter out = getResponse().getWriter() ;
		out.write(ConverterJSON.generate(map, ConverterJSON.filterBean("emp")).toString()) ;
		
		out.close() ;
		
		return null ;
	}*/

}
